package com.tfj.mvp.tfj.detail.surround;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.tfj.R;
import com.tfj.mvp.base.BaseActivity;
import com.tfj.mvp.tfj.detail.adapter.QuickAdapter_Addr;
import com.tfj.mvp.tfj.detail.surround.bean.KeyWordBean;
import com.tfj.widget.TrangleBubble;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Liang_Lu on 2017/12/21.
 *
 * @author HuangQiang
 * @github https://github.com/HuangQiang
 */

public class VSurroundActivity extends BaseActivity<PSurroundImpl> implements CSurround.IVSurround, PoiSearch.OnPoiSearchListener {

    @BindView(R.id.btn_showAll)
    Button btnShowAll;
    private AMap aMap = null;
    @BindView(R.id.recyclewView_keyword)
    RecyclerView recyclewViewKeyword;
    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.recyclewView_result)
    RecyclerView recyclewViewResult;
    @BindView(R.id.ll_sign)
    LinearLayout llSign;
    @BindView(R.id.ll_tel)
    LinearLayout llTel;
    private int checkIndex = 0;
    private UiSettings mUiSettings;
    private PoiSearch.Query query = null;
    private PoiSearch poiSearch = null;
    private List<PoiItem> poiItems_search = new ArrayList<PoiItem>();
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleText("周边配套");
        initMap();
        //关键词
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclewViewKeyword.setLayoutManager(linearLayoutManager);
        recyclewViewKeyword.setAdapter(quickAdapter_keyWord);
        List<KeyWordBean> keyWordBeans = new ArrayList<>();
        keyWordBeans.add(new KeyWordBean("公交"));
        keyWordBeans.add(new KeyWordBean("医院"));
        keyWordBeans.add(new KeyWordBean("购物"));
        keyWordBeans.add(new KeyWordBean("银行"));
        quickAdapter_keyWord.replaceData(keyWordBeans);
        //检索结果
        LinearLayoutManager linearLayoutManager_result = new LinearLayoutManager(this);
        recyclewViewResult.setLayoutManager(linearLayoutManager_result);
        recyclewViewResult.setAdapter(quickAdapter_addr);
        poiSearch(quickAdapter_keyWord.getItem(checkIndex).getName());
    }

    private void poiSearch(String keyword) {
        query = new PoiSearch.Query(keyword, "", "");
        //默认显示三个
        query.setPageNum(1);//设置查询页码
        poiSearch = new PoiSearch(this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(119.969289, 31.818), 3000));//设置周边搜索的中心点以及半径
        poiSearch.searchPOIAsyn();//调用 PoiSearch 的 searchPOIAsyn() 方法发送请求。
        poiSearch.setOnPoiSearchListener(this);
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_surround;
    }

    @Override
    public void createPresenter() {
        mPresenter = new PSurroundImpl(mContext, this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    private void initMap() {
        if (mapView != null) {
            aMap = mapView.getMap();
            mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
            mUiSettings.setScaleControlsEnabled(false);//控制比例尺控件是否显示
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setCompassEnabled(false);
            mUiSettings.setRotateGesturesEnabled(false);
            mUiSettings.setMyLocationButtonEnabled(false);//隐藏原有定位按钮
        }
    }

    //检索结果
    private QuickAdapter_KeyWord quickAdapter_keyWord = new QuickAdapter_KeyWord();
    //检索结果
    private QuickAdapter_Addr quickAdapter_addr = new QuickAdapter_Addr(R.layout.item_addr_surround);
    private ArrayList<MarkerOptions> markerOptionlst = new ArrayList<MarkerOptions>();
    private List<Marker> mList = new ArrayList<Marker>();

    public void addMarker(LatLng latLng, String title) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        TrangleBubble trangleBubble = new TrangleBubble(this);
        trangleBubble.setClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(VSurroundActivity.class);
            }
        });
        trangleBubble.setText(title);
        markerOption.icon(BitmapDescriptorFactory.fromView(trangleBubble)).draggable(false);
        markerOption.visible(true);
        markerOption.setFlat(false);//设置marker平贴地图效果
        markerOptionlst.add(markerOption);
    }

    //重新刷新红包之前把之前的红包都清掉
    public void removeAllMarker() {
        if (aMap.getMapScreenMarkers().size() > 0) {
            for (int i = 0; i < aMap.getMapScreenMarkers().size(); i++) {
                aMap.getMapScreenMarkers().get(i).setVisible(false);
            }
        }
        aMap.clear();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        mapView.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_sign, R.id.ll_tel,R.id.btn_showAll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_sign:
                break;
            case R.id.ll_tel:
                break;
            case R.id.btn_showAll:
                quickAdapter_addr.replaceData(poiItems_search);
                btnShowAll.setVisibility(View.GONE);
                break;
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {  // 搜索poi的结果
                if (result.getQuery().equals(query)) {
                    PoiResult poiResult = result;
                    //final ArrayList<PoiAddressBean> data = new ArrayList<PoiAddressBean>();//自己创建的数据集合
                    // 取得搜索到的poiitems有多少页

                     poiItems_search = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    Log.i(TAG, JSONObject.toJSONString(poiItems_search));

                    if (poiItems_search != null && poiItems_search.size() > 0) {
                            btnShowAll.setVisibility(poiItems_search.size()>=6?View.VISIBLE:View.GONE);
                        quickAdapter_addr.replaceData(poiItems_search.size()>=6?poiItems_search.subList(0,6):poiItems_search);
                    }
                    removeAllMarker();
                    for (PoiItem item : poiItems_search) {
                        //获取经纬度对象
                        LatLonPoint llp = item.getLatLonPoint();
                        double lon = llp.getLongitude();
                        double lat = llp.getLatitude();
                        String title = item.getTitle();
                        int distance = item.getDistance();
                        addMarker(new LatLng(lat, lon), title);
                        Log.i(TAG, "title-->" + title);
                        Log.i(TAG, "distance-->" + distance + "m");
                    }
                    mList = aMap.addMarkers(markerOptionlst, false);
                    Log.i(TAG, JSONObject.toJSONString(mList));
                    aMap.moveCamera(CameraUpdateFactory
                            .newLatLngZoom(new LatLng(result.getBound().getCenter().getLongitude(), result.getBound().getCenter().getLatitude()), 15f));
                }
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    public class QuickAdapter_KeyWord extends BaseQuickAdapter<KeyWordBean, BaseViewHolder> {
        public QuickAdapter_KeyWord() {
            super(R.layout.item_keyword);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, final KeyWordBean item) {
            viewHolder.setText(R.id.textView_keyword, item.getName());
            TextView textView_keyword = viewHolder.getView(R.id.textView_keyword);
            if (viewHolder.getAdapterPosition() == checkIndex) {
                textView_keyword.setTextColor(getResources().getColor(R.color.mainColor));
            } else {
                textView_keyword.setTextColor(getResources().getColor(R.color.black));
            }
            textView_keyword.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkIndex = viewHolder.getAdapterPosition();
                    quickAdapter_keyWord.notifyDataSetChanged();
                    poiSearch(item.getName());
                }
            });
        }
    }

}
